module(..., package.seeall)
----------------------------------------------------------------------------------
--
-- scenetemplate.lua
--
----------------------------------------------------------------------------------

local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local ui = require("ui")
local gui = require "Stage14.Stage14HomeGui".new()
local wEasing = require "wEasing"

----------------------------------------------------------------------------------
-- 
--	NOTE:
--	
--	Code outside of listener functions (below) will only be executed once,
--	unless storyboard.removeScene() is called.
-- 
---------------------------------------------------------------------------------

---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view


end




-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
	local mainGroup = self.view
	
------------------------------------------------------------
local backgroundGroup,stageButtonGroup,homeButtonGroup,generateItemsGroup
local bg,replayButton,leftButton,centerButton,rightButton
local okImage,goodImage,perfectImage
local backgroundButton = {}


local _score
local totalTimer
local totalTime,readyTime = 500,1000
local deltaTotalTime

local score
local _tran, _tran1,_tran2
local tFormer
local timeScore ={}
local scoreText
local timeTransition = 500
local countTurn = 0
local isTouchOk = false
-- local isTouchTrue = false
local pinImage = {}
local deltaDistance
local yBallance = gui.pinImage.y
local isGo

-----------------------------------------------------------------------------
function init()
	pauseButton.isVisible = true
	replayButton.isVisible = true
	isGo = false
	goText.alpha = 0
	_score = {14,16,18,20,22}
	totalTime = 1000
	deltaTotalTime = totalTime + 1000
	deltaDistance = 5
	_gameOver.alpha = 0
	
	
	pinImage[1].x = gui.pinImage.x[1]
	pinImage[1].y = gui.pinImage.y
	pinImage[2].x = gui.pinImage.x[2]
	pinImage[2].y = gui.pinImage.y
	
	pinImage[3].x = gui.pinImage.x[1]
	pinImage[3].y = gui.pinImage.y
	pinImage[4].x = gui.pinImage.x[2]
	pinImage[4].y = gui.pinImage.y
	
	tFormer = system.getTimer()
	pinImage[1].alpha = 1
	pinImage[2].alpha = 1
	pinImage[3].alpha = 0
	pinImage[4].alpha = 0
	totalTimer = timer.performWithDelay(100,manageTotalTimer,0)
end
--------------------------- create group -------------------------------
	backgroundGroup = display.newGroup()
	stageButtonGroup = display.newGroup()
	homeButtonGroup = display.newGroup()
	generateItemsGroup = display.newGroup()
	
--------------------------------------------------------------------
-------------------------- handle function ------------------------------
function manageTotalTimer()
	deltaTotalTime = deltaTotalTime - 100
	if(deltaTotalTime < 1000 and deltaTotalTime >= 0 and isGo == false)then
		goText.alpha = 1
	elseif(deltaTotalTime < 0)then
		
		goText.alpha = 0
		if(isGo == false)then
			isGo = true
			backgroundButton[1]:addEventListener("tap",onTapButton)
			backgroundButton[2]:addEventListener("tap",onTapButton)
			Runtime:addEventListener("enterFrame",onEnterFrame)
		end
		if(totalTime > 50)then
			totalTime = totalTime - 50
		end
		deltaTotalTime = totalTime
		if(pinImage[1].y >= pinImage[2].y)then
			pinImage[1].y = pinImage[1].y + 3*deltaDistance
			pinImage[2].y = pinImage[2].y - 3*deltaDistance
		else
			pinImage[1].y = pinImage[1].y - 3*deltaDistance
			pinImage[2].y = pinImage[2].y + 3*deltaDistance
		end
		if(pinImage[3].y >= pinImage[4].y)then
			pinImage[3].y = pinImage[3].y + 3*deltaDistance
			pinImage[4].y = pinImage[4].y - 3*deltaDistance
		else
			pinImage[3].y = pinImage[3].y - 3*deltaDistance
			pinImage[4].y = pinImage[4].y + 3*deltaDistance
		end
	end
end

function gameOver()
	-- _gameOver.alpha = 1
	local temp = math.round(timeScore/1000)
	local star
	if(temp < 14)then
		star = 0
	elseif(temp >= 14 and temp < 16)then
		star = 1
	elseif(temp >= 16 and temp < 18)then
		star = 2
	elseif(temp >= 18 and temp < 20)then
		star = 3
	elseif(temp >= 20 and temp < 22)then
		star = 4
	elseif(temp >= 22)then
		star = 5
	end
	local g1
	g1 = require "popup.popupWin".new(temp,star,_score,onReplayButtonTap)
	transition.to(g1,{time = 200,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic})
end

function onTapButton(event)
	local t = event.target
	if(t.id == 1)then
		pinImage[1].y = pinImage[1].y + deltaDistance
		pinImage[2].y = pinImage[2].y - deltaDistance
		pinImage[3].y = pinImage[3].y + deltaDistance
		pinImage[4].y = pinImage[4].y - deltaDistance
	elseif(t.id == 2)then
		pinImage[1].y = pinImage[1].y - deltaDistance
		pinImage[2].y = pinImage[2].y + deltaDistance
		pinImage[3].y = pinImage[3].y - deltaDistance
		pinImage[4].y = pinImage[4].y + deltaDistance
	end
end

function finishedGame()
	print("victory")
end

function showImageResult(deltaTime)
	
	if(deltaTime >= 0 and deltaTime < 0.4*totalTime)then
		perfectImage.alpha = 1
		goodImage.alpha = 0
		okImage.alpha = 0
	elseif(deltaTime >= 0.4*totalTime and deltaTime < 0.6*totalTime)then
		perfectImage.alpha = 0
		goodImage.alpha = 1
		okImage.alpha = 0
	elseif(deltaTime >= 0.6*totalTime)then
		perfectImage.alpha = 0
		goodImage.alpha = 0
		okImage.alpha = 1
	end
	
end

function onEnterFrame()
	if(pinImage[1].y >= 180 or pinImage[2].y >= 180)then
		timer.cancel(totalTimer)
		Runtime:removeEventListener("enterFrame",onEnterFrame)
		backgroundButton[1]:removeEventListener("tap",onTapButton)
		backgroundButton[2]:removeEventListener("tap",onTapButton)
		timeScore = system.getTimer() - tFormer
		
		gameOver()
	end
	if(pinImage[1].y > pinImage[2].y)then
		pinImage[1].alpha = 0
		pinImage[2].alpha = 1
		pinImage[3].alpha = 1
		pinImage[4].alpha = 0
	elseif(pinImage[1] == pinImage[2])then
		pinImage[1].alpha = 1
		pinImage[2].alpha = 1
		pinImage[3].alpha = 0
		pinImage[4].alpha = 0
	else
		pinImage[1].alpha = 1
		pinImage[2].alpha = 0
		pinImage[3].alpha = 0
		pinImage[4].alpha = 1
	end
end

function onReplayButtonTap()
	if(totalTimer ~= nil)then
		timer.cancel(totalTimer)
	end
	if(isGo == true)then
		Runtime:removeEventListener("enterFrame",onEnterFrame)
		backgroundButton[1]:removeEventListener("tap",onTapButton)
		backgroundButton[2]:removeEventListener("tap",onTapButton)
	end
	init()
end

function checkWin()
	
end

function onStartPopup()
	timer.pause(totalTimer)
	if(isGo == true)then
		Runtime:removeEventListener("enterFrame",onEnterFrame)
	end
end

function onResumeFromPopup()
	timer.resume(totalTimer)
	if(isGo == true)then
		Runtime:addEventListener("enterFrame",onEnterFrame)
	end
end

do -------------------- background and button ---------------------
bg = display.newImageRect(backgroundGroup, gui.bg.fn, gui.bg.w, gui.bg.h)
	bg.x = gui.bg.x
	bg.y = gui.bg.y

replayButton = ui.newButton({
	defaultSrc = gui.replayButton.fn,
	overSrc = gui.replayButton.fn,
	defaultX = gui.replayButton.w,
	defaultY = gui.replayButton.h,
	overX = gui.replayButton.w,
	overY = gui.replayButton.h,
	x = gui.replayButton.x,
	y = gui.replayButton.y,
	
	onRelease = onReplayButtonTap
})
pauseButton = ui.newButton({
	defaultSrc = gui.pauseButton.fn,
	overSrc = gui.pauseButton.fn,
	defaultX = gui.pauseButton.w,
	defaultY = gui.pauseButton.h,
	overX = gui.pauseButton.w*1.2,
	overY = gui.pauseButton.h*1.2,
	x = gui.pauseButton.x,
	y = gui.pauseButton.y,
	
	onRelease = function()
		local g2 = require "popup.popupPause".new(onResumeFromPopup,onReplayButtonTap)
		local group2 = display.newGroup()
		group2:insert(g2)
		
		group2.y = -300
		transition.to(group2,{time = 1000,alpha = 1, x = 0, y = 0, transition = wEasing.easeOutElastic, onStart = onStartPopup })
		-- backgroundGroup:insert(group2)
	end
})

backgroundButton[1] = display.newImageRect(stageButtonGroup,gui.leftButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[1].x = gui.leftButton.x
	backgroundButton[1].y = gui.leftButton.y
	backgroundButton[1].id = 1

	
backgroundButton[2] = display.newImageRect(stageButtonGroup,gui.rightButton.fn,gui.buttonPosition.w,gui.buttonPosition.h)
	backgroundButton[2].x = gui.rightButton.x
	backgroundButton[2].y = gui.rightButton.y
	backgroundButton[2].id = 2

pinImage[1] = display.newImageRect(stageButtonGroup,gui.pinImage.fn[1],gui.pinImage.w,gui.pinImage.h)
	pinImage[1].x = gui.pinImage.x[1]
	pinImage[1].y = gui.pinImage.y
	pinImage[1].alpha = 0

pinImage[2] = display.newImageRect(stageButtonGroup,gui.pinImage.fn[1],gui.pinImage.w,gui.pinImage.h)
	pinImage[2].x = gui.pinImage.x[2]
	pinImage[2].y = gui.pinImage.y
	pinImage[2].alpha = 0
pinImage[3] = display.newImageRect(stageButtonGroup,gui.pinImage.fn[2],gui.pinImage.w,gui.pinImage.h)
	pinImage[3].x = gui.pinImage.x[1]
	pinImage[3].y = gui.pinImage.y
	pinImage[3].alpha = 0

pinImage[4] = display.newImageRect(stageButtonGroup,gui.pinImage.fn[2],gui.pinImage.w,gui.pinImage.h)
	pinImage[4].x = gui.pinImage.x[2]
	pinImage[4].y = gui.pinImage.y
	pinImage[4].alpha = 0


okImage = display.newImageRect(homeButtonGroup,gui.okImage.fn,gui.okImage.w,gui.okImage.h)
	okImage.x = gui.okImage.x
	okImage.y = gui.okImage.y
	okImage.alpha = 0

goodImage = display.newImageRect(homeButtonGroup,gui.goodImage.fn,gui.goodImage.w,gui.goodImage.h)
	goodImage.x = gui.goodImage.x
	goodImage.y = gui.goodImage.y
	goodImage.alpha = 0

perfectImage = display.newImageRect(homeButtonGroup,gui.perfectImage.fn,gui.perfectImage.w,gui.perfectImage.h)
	perfectImage.x = gui.perfectImage.x
	perfectImage.y = gui.perfectImage.y
	perfectImage.alpha = 0
	
end
	
mainGroup:insert(backgroundGroup)
mainGroup:insert(stageButtonGroup)
mainGroup:insert(generateItemsGroup)
mainGroup:insert(homeButtonGroup)
mainGroup:insert(pauseButton)
mainGroup:insert(replayButton)

do ------------------------------------ text -----------------
readyText = display.newText(mainGroup, "2",160 , 150, gui.timer.font, gui.timer.fontSize+20)
	readyText:setTextColor(255,0,0)
	readyText.alpha = 0
-- goText = display.newText(mainGroup, "GO", 160 -30, 150, gui.timer.font, gui.timer.fontSize+20)
	-- goText:setTextColor(255,0,0)
	-- goText.alpha = 0
goText = display.newImageRect(mainGroup,gui.goImage.fn,gui.goImage.w,gui.goImage.h)
	goText.x = gui.goImage.x
	goText.y = gui.goImage.y
	goText.alpha = 0

timerText = display.newText(mainGroup,"",50,50,gui.timer.font,gui.timer.fontSize)
	timerText:setTextColor(255,0,0)
	timerText.alpha = 0
	
_gameOver = display.newText(homeButtonGroup,"GAME OVER", gui.score.x, gui.score.y, gui.score.font, gui.score.fontSize)
	_gameOver.x = display.contentCenterX
	_gameOver.y = display.contentCenterY
	_gameOver:setTextColor(unpack(gui.score.color))
	_gameOver.alpha = 0
------------------------------- score -------------------------------
scoreText = display.newText(gui.score.text, gui.score.left, gui.score.top, gui.score.font, gui.score.fontSize)
	scoreText:setTextColor(gui.score.red, gui.score.green, gui.score.red, gui.score.alpha)
	scoreText.x = gui.score.x
	scoreText.y = gui.score.y
	scoreText.alpha = 0
homeButtonGroup:insert(scoreText)
end
------------------------------------- run test --------------------------------------
init()


----------------------------- end run test ------------------------------------------------
-----------------------------------------------------------------------------
	
end


-- Called when scene is about to move offscreen:
function scene:exitScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. stop timers, remove listeners, unload sounds, etc.)
	
	-----------------------------------------------------------------------------
	
end


-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
	local group = self.view
	
	-----------------------------------------------------------------------------
	
	--	INSERT code here (e.g. remove listeners, widgets, save state, etc.)
	
	-----------------------------------------------------------------------------
	
end

---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------

-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )

-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )

-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )

-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )

---------------------------------------------------------------------------------

return scene